package backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class restoreIpAddresses {
    List<String> result = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        backtracking(new StringBuilder(s), 0, 0);
        return result;
    }
    public void backtracking(StringBuilder s, int start, int count){
        if (count == 3){
            if (isValid(s, start, s.length()-1)){
                result.add(s.toString());
            }
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (isValid(s, start, i)){
                s.insert(i + 1, '.');
                backtracking(s, i + 2, count + 1);
                s.deleteCharAt(i + 1);
            } else {
                break;
            }
        }
    }
    public boolean isValid(StringBuilder s, int start, int end){
        if (start > end){
            return false;
        }
        if (s.charAt(start) == '0' && start != end){
            return false;
        }
        int num = 0;
        for(int i = start; i <= end; i++){
            int digit = s.charAt(i) - '0';
            num = num * 10 + digit;
            if(num > 255)
                return false;
        }
        return true;
    }
}
